-- Thanks: https://github.com/sathishmanohar/quick-buffer-jump
local M = {}

local color = require('utils.color')
local t = require('utils.table')
local misc = require('utils.misc')
local futil = require('utils.file')

function M.quick_select(buffers)
    local api = vim.api
    local lines = {}
    local buffer_map = {}  -- Table to map line numbers to file name
    local alphabet = misc.get_alphabet()
    local alphabet_count = 1

    -- Create buffer for the floating window
    local float_buf = api.nvim_create_buf(false, true)

    t.foreach(buffers,function(buf)
        local name = api.nvim_buf_get_name(buf)
        local alphabet_label = alphabet:sub(alphabet_count, alphabet_count)
        local label = alphabet_label .. ' + ' .. futil.split_file_name(name,65)
        t.append(lines,label)
        buffer_map[#lines] = buf

        -- Map the alphabet key to the fn
        local map_cmd = '<cmd>lua vim.api.nvim_win_close(vim.fn.bufwinid('..float_buf..'), true); vim.api.nvim_set_current_buf('..buf..')<CR>'
        api.nvim_buf_set_keymap(float_buf, 'n', alphabet_label, map_cmd, {noremap = true, silent = true})

        alphabet_count = (alphabet_count % #alphabet) + 1
    end)

    local max_height = #lines + 1
    local width = 70
    local row = (vim.o.lines - max_height) / 2
    local col = (vim.o.columns - width) / 2

    -- Create the floating window
    local float_win = api.nvim_open_win(float_buf, true, {
        title = "Modified buffers",
        title_pos = "right",
        relative = 'editor',
        width = width,
        height = max_height,
        row = row,
        col = col,
        style = 'minimal',
        border = 'shadow'
    })

    --api.nvim_win_set_option(float_win, 'cursorline', true)
    api.nvim_set_option_value('cursorline', true, {win=float_win})
    api.nvim_buf_set_lines(float_buf, 0, -1, false, lines)

    -- Apply highlights for each alphabet label
    t.foreach(lines,function(_,i)
        local start_pos = 0
        local end_pos = 1
        api.nvim_buf_add_highlight(float_buf, -1, 'AlphabetLabel', i - 1, start_pos, end_pos)
    end)

    -- Store the file map in a buffer-local variable
    api.nvim_buf_set_var(float_buf, "buffer_map", buffer_map)

    -- Key mapping for Enter to switch to the file of the current line
    vim.api.nvim_create_user_command('QuickBufferSelectorEnter', function()
        local buf_id = vim.api.nvim_buf_get_var(float_buf, "buffer_map")[vim.api.nvim_win_get_cursor(0)[1]]
        vim.api.nvim_win_close(vim.fn.bufwinid(float_buf), true)
        vim.api.nvim_set_current_buf(buf_id)
    end, {})

    api.nvim_buf_set_keymap(float_buf, 'n', '<CR>', "<cmd>QuickBufferSelectorEnter<CR>", {noremap = true, silent = true})

end

return M
-- EOP
